use std::{thread, time::Duration};
use wayland_client::{
    protocol::{wl_compositor::WlCompositor, wl_surface::WlSurface},
    Display, GlobalManager,
};
use uinput::event::keyboard;
use uinput::Device;

fn main() {
    // 初始化 Wayland 连接
    let display = Display::connect_to_env().expect("Failed to connect to a Wayland display");
    let event_queue = display.create_event_queue();
    let attached_display = (*display).clone().attach(event_queue.token());

    // 获取 Compositor
    let global_manager = GlobalManager::new(&attached_display);
    event_queue.sync_roundtrip(&mut (), |_, _, _| {}).unwrap();
    let compositor = global_manager
        .instantiate_exact::<WlCompositor>(1)
        .expect("Failed to get compositor");

    // 创建 Surface（窗口）
    let surface = compositor.create_surface();

    // 初始化虚拟键盘
    let mut keyboard = uinput::default().unwrap()
        .create().unwrap()
        .name("virtual-keyboard").unwrap()
        .with_keys(&[
            keyboard::Key::A,
            keyboard::Key::B,
            keyboard::Key::C,
            keyboard::Key::Enter,
        ]).unwrap()
        .build().unwrap();

    // 模拟一个按钮点击事件来发送键盘输入
    simulate_key_press(&mut keyboard);

    // Wayland 事件循环（保持窗口显示）
    loop {
        event_queue
            .dispatch(&mut (), |_, _, _| {})
            .expect("Failed to dispatch event");
        thread::sleep(Duration::from_millis(100));
    }
}

// 模拟键盘按键
fn simulate_key_press(keyboard: &mut Device) {
    // 模拟按键 "ABC" 后回车
    keyboard.press(&keyboard::Key::A).unwrap();
    thread::sleep(Duration::from_millis(100));
    keyboard.release(&keyboard::Key::A).unwrap();
    keyboard.press(&keyboard::Key::B).unwrap();
    thread::sleep(Duration::from_millis(100));
    keyboard.release(&keyboard::Key::B).unwrap();
    keyboard.press(&keyboard::Key::C).unwrap();
    thread::sleep(Duration::from_millis(100));
    keyboard.release(&keyboard::Key::C).unwrap();

    // 模拟回车键
    keyboard.press(&keyboard::Key::Enter).unwrap();
    thread::sleep(Duration::from_millis(100));
    keyboard.release(&keyboard::Key::Enter).unwrap();
}
